import { Graph, useGraphInstance } from '@antv/xflow';
import { debounce } from 'lodash-es';

import { setGraphJsonToStorage } from '@/utils/graph';


// 是否可以交互
const interactingStateAtom = atom<boolean>({
  default: true,
  key: 'interactingState'
});

export const useInteracting = () => {
  const [interacting, setInteracting] = useRecoilState(interactingStateAtom);

  return {
    interacting,
    setInteracting
  };
};

let tempGraph: Graph | null = null;

export const useGraph = () => {
  const graph = useGraphInstance();
  const { interacting, setInteracting } = useInteracting();

  useEffect(() => {
    if (graph) {
      tempGraph = graph;
    }
  }, [graph]);

  // eslint-disable-next-line react-hooks/exhaustive-deps
  const getGraphJson = useCallback(() => {
    return tempGraph?.toJSON();
  }, []);

  // eslint-disable-next-line react-hooks/exhaustive-deps
  const saveGraph = useCallback(
    debounce(() => {
      const flowId = new URLSearchParams(window.location.search).get('flowId') as string;
      const data = getGraphJson();
      setGraphJsonToStorage(flowId, data!);
    }, 100),
    [getGraphJson]
  );

  return {
    graph,
    /** 获取画布配置json */
    getGraphJson,
    /** 保存画布到本地存储 */
    saveGraph,
    /** 画布是否可以交互 */
    interacting,
    setInteracting
  };
};
